﻿using AutoMapper;
using ERPPublic;
using MediatR;
using Newtonsoft.Json;
using SqlSugar;
using WarehouseManagement.Application.Command.WarehouseSAppCommand;
using WarehouseManagement.Domain.DTO;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.WarehouseSAppCommandHandler
{
    /// <summary>
    /// 确认入库修改中介者
    /// </summary>
    public class ConfirmWarehouseentryCommandHandler:IRequestHandler<ConfirmWarehouseentryCommand,int>
    {
        private readonly lnterfaceWarehouseSAppRepository _warehouseSAppRepository;//仓库入库申请表
        private readonly lnterfaceStorageProductRepository _storageProductsRepository;//仓库入库申请产品明细表
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public ConfirmWarehouseentryCommandHandler(lnterfaceWarehouseSAppRepository warehouseSAppRepository, lnterfaceStorageProductRepository storageProductsRepository, IMapper mapper, ISqlSugarClient db)
        {
            _warehouseSAppRepository = warehouseSAppRepository;
            _storageProductsRepository = storageProductsRepository;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(ConfirmWarehouseentryCommand request, CancellationToken cancellationToken)
        {
            //开始事务
            db.Ado.BeginTran();
            try
            {
                //修改仓库入库申请表
                var list = (await _warehouseSAppRepository.GetAll()).First(x => x.ShippRequestAppId == request.dto.ShippRequestAppId);
                var a = await _warehouseSAppRepository.UpdateAsync(mapper.Map(request.dto, list));
                //查询入库申请表里的产品明细
                var list1 = (await _storageProductsRepository.GetAll()).Where(x => x.StorageNumber == request.dto.StorageNumber).ToList();
                //删除原有产品明细
                await _storageProductsRepository.DelRange(list1);
                //添加新的产品明细
                foreach (var item in request.dto.list)
                {
                    StorageProduct storageProduct = new StorageProduct()
                    {
                        StorageNumber = list.StorageNumber,
                        PNumber = item.PNumber,
                        PName = item.PName,
                        PSpec = item.PSpec,
                        PUnit = item.PUnit,
                        PPrice = item.PPrice,
                        SPConfirmNum = item.SPConfirmNum,
                        SumNum=item.SumNum,
                        SumPrice = item.SumPrice,
                        Batch = item.Batch,
                        CreateDate = item.CreateDate,
                        ValidDate = item.ValidDate,
                        ArriveDate = item.ArriveDate,
                        WrapName = item.WrapName,
                        Remark = item.Remark
                    };
                    await _storageProductsRepository.AddAsync(storageProduct);
                }
                MessageCreateDto dto = new MessageCreateDto();
                dto.MType = "确认入库";
                dto.Title = "确认入库修改";
                dto.SendTime = DateTime.Now;
                await MessageCreates(dto);
                //提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                //回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public async Task<int> MessageCreates(MessageCreateDto dtos)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);
            string chanpin = "http://116.205.121.197:8000/erpcp/api/Message/SendMessage";
            string jsonstr = JsonConvert.SerializeObject(dtos);
            string postReponse = await cilent.PostAsync(chanpin, jsonstr);
            return 1;
        }
    }
}
